<template>
	<view class="bg-[var(--page-bg-color)] min-h-screen overflow-hidden order-list" :style="themeColor()">
		<view class="fixed left-0 top-0 right-0 z-10 bg-[#fff]" v-if="statusLoading">
			<view class="py-[14rpx] flex items-center justify-between px-[20rpx]">
				<view class="flex-1 bg-[#fafafa] p-[10rpx] rounded-[8rpx] mr-[20rpx]">
					创建时间: {{ create_time_str }}
				</view>
				<view class="nc-iconfont nc-icon-shaixuanV6xx !text-[30rpx] leading-[36rpx] text-[var(--text-color-light6)]"
					@click="handleSelectOrderSearch"></view>

			</view>

			<view class="bg-[var(--page-bg-color)] p-[20rpx]">
				当前账户欠款金额{{ fen2yuan(memberDataInfo.arrearsPrice) }}元
			</view>
		</view>

		<mescroll-body ref="mescrollRef" :top="'170rpx'" @init="mescrollInit" :down="{ use: false }" @up="getShopOrderFn">
			<view class="sidebar-margin pt-[var(--top-m)]" v-if="list.length">
				<template v-for="(item, index) in list" :key="index">
					<view class="mb-[var(--top-m)] card-template">
						<view>
							<view class="flex justify-between items-center">
								<view class="text-[#303133] text-[28rpx] font-400 leading-[36rpx]">
									<text>销售时间:</text>
									<text class="ml-[10rpx]">{{ timeFormat(item?.tradeTime, 'yyyy-mm-dd hh:MM:ss') }}</text>

								</view>
								<view class="text-[var(--primary-color)] text-[28rpx] leading-[34rpx]"
									:class="{ 'text-primary': item.status == 0, '!text-[var(--text-color-light9)]': item.status == 10 || item.status == 40 }">
									{{ formatOrderStatus(item) }}</view>
							</view>
							<u-line dashed margin="10rpx 0"></u-line>
							<view class="flex justify-between items-center">
								<view class="text-[#303133] text-[28rpx] font-400 leading-[36rpx] ">
									<text>{{ t('orderNo') }}:</text>
									<text class="ml-[10rpx]">{{ item.no }}</text>
									<text class="text-[#303133] text-[28rpx] font-400 nc-iconfont nc-icon-fuzhiV6xx1 ml-[11rpx]"
										@click.stop="copy(item.no)"></text>
								</view>

								<view class="text-[#303133] text-[28rpx] font-400 leading-[36rpx] ">
									<text class="ml-[10rpx]">{{ formatOrderType(item) }}</text>
								</view>
							</view>
							<u-line dashed margin="10rpx 0"></u-line>
							<block v-for="(subItem, index) in item.items" :key="index">
								<view class="flex box-border mt-[20rpx]" @click.stop="selectOnlyGoods(subItem)">
									<view class="self-center w-[34rpx] mr-[24rpx] h-[60rpx] flex items-center"
										@click.stop="selectOnlyGoods(subItem)">
										<text
											class=" iconfont text-color text-[34rpx] w-[34rpx] h-[34rpx] rounded-[17rpx] overflow-hidden shrink-0"
											:class="{ 'iconxuanze1': subItem.checked, 'bg-[#F5F5F5]': !subItem.checked }">
										</text>
									</view>
									<u--image width="150rpx" height="150rpx" :radius="'var(--goods-rounded-big)'"
										:src="img(subItem.picUrl ? subItem.picUrl : '')" mode="aspectFill">
										<template #error>
											<image class="w-[150rpx] h-[150rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
												:src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill"></image>
										</template>
									</u--image>
									<view class="ml-[20rpx] flex flex-1 flex-col justify-between box-border">
										<view class="flex justify-between items-baseline">
											<view class="max-w-[322rpx]  text-[32rpx] leading-[40rpx] font-bold truncate text-[#303133]">
												<view class="brand-tag">
													{{ formatSpuType(subItem.spuType)
													}}
												</view>{{
													subItem.spuName }}
											</view>

											<!-- <view class="text-right leading-[42rpx] ml-[10rpx] ">
												<uni-tooltip :content="'实售单价'" @click.stop placement="left">
													<uni-icons type="info" size="14"></uni-icons>
													<template #content>
														<view class="w-100rpx">
															实售单价
														</view>
													</template>
												</uni-tooltip>
												<text class="text-[22rpx] price-font">￥</text>
												<text class="text-[36rpx] font-500 price-font">{{
													parseFloat(diyGoods.fen2yuan(subItem.singlePrice)).toFixed(2).split('.')[0]
												}}</text>
												<text class="text-[22rpx] font-500 price-font">.{{
													parseFloat(diyGoods.fen2yuan(subItem.singlePrice)).toFixed(2).split('.')[1]
												}}</text>
											</view> -->
										</view>
										<view class="flex justify-between items-center text-[#303133] ">
											<view
												class="text-[24rpx] text-[var(--text-color-light6)] font-400 truncate leading-[34rpx] max-w-[369rpx] ">
												<text v-if="subItem?.properties">{{ skuSpecFormat(subItem.properties) }}</text>
												<template v-if="subItem?.spuType == 2">
													<text v-if="subItem?.properties">|</text>
													<text>{{
														filterCardAttributes(subItem, true, true) }}</text>
												</template><text
													v-if="subItem?.properties && formatAdminAfterSaleStatus(subItem?.afterSaleStatus)">|</text>
												<text>{{
													formatAdminAfterSaleStatus(subItem?.afterSaleStatus) }}</text>
											</view>




											<!-- <text class="line-through text-[28rpx]">￥{{
												fen2yuan(subItem.price) }}</text> -->
										</view>
										<view class="flex justify-between items-center  text-[#303133] ">
											<view class="flex items-baseline flex-wrap  ">

												<view class="text-[22rpx] font-400 leading-[30rpx] text-[#303133]"
													v-if="subItem.leavePrice > 0">
													剩余欠款：
												</view>
												<view class="leading-[1] text-[var(--price-text-color)]  mr-[6rpx]"
													v-if="subItem.leavePrice > 0">
													<text class="text-[22rpx] leading-[26rpx] price-font">￥</text>
													<text class="text-[36rpx] font-500 leading-[40rpx] price-font">{{
														parseFloat(diyGoods.fen2yuan(subItem.leavePrice)).toFixed(2).split('.')[0] }}</text>
													<text class="text-[22rpx] font-500 leading-[28rpx] price-font">.{{
														parseFloat(diyGoods.fen2yuan(subItem.leavePrice)).toFixed(2).split('.')[1] }}</text>
												</view>

											</view>
											<text class="text-right text-[28rpx] font-400 w-[90rpx] leading-[36rpx]">x{{ subItem.count
											}}</text>
										</view>

									</view>
								</view>
							</block>
						</view>
						<view class="flex justify-end items-center ">
							<view class="flex items-baseline flex-wrap justify-end ">

								<view class="text-[22rpx] font-400 leading-[30rpx] text-[#303133]" v-if="item.leavePrice > 0">总欠款金额：
								</view>
								<view class="leading-[1] text-[var(--price-text-color)]  mr-[6rpx]" v-if="item.leavePrice > 0">
									<text class="text-[22rpx] leading-[26rpx] price-font">￥</text>
									<text class="text-[36rpx] font-500 leading-[40rpx] price-font">{{
										parseFloat(diyGoods.fen2yuan(item.leavePrice)).toFixed(2).split('.')[0] }}</text>
									<text class="text-[22rpx] font-500 leading-[28rpx] price-font">.{{
										parseFloat(diyGoods.fen2yuan(item.leavePrice)).toFixed(2).split('.')[1] }}</text>
								</view>

							</view>
						</view>
						<!-- 会员信息 -->
						<!-- <memberInfo :member="item?.user" v-if="item?.user"></memberInfo> -->
						<!-- 订单备注 -->
						<remarkInfo :order="item"></remarkInfo>
					</view>
				</template>
			</view>
			<mescroll-empty v-if="!list.length && loading" :option="{ tip: '暂无订单' }"></mescroll-empty>
		</mescroll-body>
		<view v-if="list.length"
			class="pl-[30rpx] pr-[20rpx] flex h-[118rpx] items-center bg-[#fff] fixed z-99999 left-0 right-0 bottom-[0rpx] box-solid pb-ios justify-between border-0 border-t-[2rpx] border-solid border-[#f6f6f6]">
			<view class="flex items-center">

			</view>
			<view class="flex items-center">
				<view class="flex-1 flex items-center justify-between">
					<view class="mr-[20rpx]">
						<view class="flex items-center text-[var(--price-text-color)] leading-[45rpx]">
							<view class="font-400 text-[#303133] text-[32rpx]">合计：</view>
							<text class="text-[var(--price-text-color)] price-font text-[38rpx] font-bold">
								￥{{ parseFloat(diyGoods.fen2yuan(total.order_money)).toFixed(2) }}
							</text>
						</view>

					</view>

					<!-- #ifdef H5 || APP-PLUS -->
					<button
						class="w-[240rpx] h-[84rpx] font-500 text-[32rpx] leading-[84rpx] !text-[#fff] m-0 rounded-full primary-btn-bg remove-border"
						@click="settlement">批量还款</button>
					<!-- #endif -->

					<!-- #ifdef MP-WEIXIN -->
					<!-- <button v-if="isBindMobile && info && !info.mobile"
						class="w-[240rpx] h-[84rpx] font-500 text-[32rpx] leading-[84rpx] !text-[#fff] m-0 rounded-full primary-btn-bg remove-border"
						open-type="getPhoneNumber" @getphonenumber="memberStore.bindMobile">结算</button> -->
					<button
						class="w-[240rpx] h-[84rpx] font-500 text-[32rpx] leading-[84rpx] !text-[#fff] m-0 rounded-full primary-btn-bg remove-border"
						@click="settlement">批量还款</button>
					<!-- #endif -->

				</view>

			</view>
		</view>
		<!-- 订单筛选 -->
		<select-order-search ref="selectOrderSearchRef" :default-date="create_time" :trade-date="trade_time"
			:time-type-list="timeTypeList" :status-tabs="orderStateList" :source-list="orderSourceList"
			:order-type-list="orderTypeList" @confirm="confirmSearchFn"></select-order-search>
		<pay ref="payRef" @close="payClose"></pay>
		<!-- #ifdef MP-WEIXIN -->
		<!-- 小程序隐私协议 -->
		<wx-privacy-popup ref="wxPrivacyPopupRef"></wx-privacy-popup>
		<!-- #endif -->
	</view>
	<!-- 水印 -->
	<watermark></watermark>
</template>

<script setup lang="ts">
import { ref, nextTick, computed, onMounted } from 'vue';
import { t } from '@/locale'
import { img, redirect, copy, } from '@/utils/common'

import { getShopOrder } from '@/addon/debt/api/shopOrder';
import MescrollBody from '@/components/mescroll/mescroll-body/mescroll-body.vue';
import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue';
import useMescroll from '@/components/mescroll/hooks/useMescroll.js';
import { onLoad, onPageScroll, onReachBottom, onShow, onUnload } from '@dcloudio/uni-app';
import { formatOrderStatus, skuSpecFormat, formatOrderType, timeFormat, filterCardAttributes, formatSpuType, formatAdminAfterSaleStatus, fen2yuan, getNowMonthDate } from "@/utils/formatting"
import { useGoods } from '@/addon/shop/hooks/useGoods'
import memberInfo from '@/addon/components/order/memberInfo.vue'
import remarkInfo from '@/addon/components/order/remarkInfo.vue';
const diyGoods = useGoods();
const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom);
const list = ref<any>([]);
const loading = ref<boolean>(false);
const statusLoading = ref<boolean>(true);
const orderState = ref('')
const orderShowType = ref('employee') //订单展示类型 employee 门店员工  member 会员
const orderStateList: any = ref([

	{
		name: '全部',
		status: undefined
	},
	{
		name: "待结清",
		status: 101
	},
	{
		name: "已结清",
		status: 102
	},
	{
		name: "已撤销",
		status: 50
	},
	{
		name: "已取消",
		status: 40
	},


]);
const orderType = ref(undefined)
const orderSource = ref(undefined)
const orderSourceList: any = ref([
	{
		name: '全部',
		status: undefined
	},
	{
		name: '门店',
		status: 4
	},
	{
		name: '商城',
		status: 5
	}
])
const orderTypeList: any = ref([
	{
		name: '全部',
		status: undefined
	},
	{
		name: '普通订单',
		status: 0
	},
	{
		name: '秒杀订单',
		status: 1
	},
	{
		name: '砍价订单',
		status: 2
	},
	{
		name: '拼团订单',
		status: 3
	},
	{
		name: '积分商城',
		status: 4
	},
	{
		name: '活动订单',
		status: 6
	}
])
const total = ref({
	order_money: 0, //订单金额

})
/** 搜索类型 */
const searchType = ref([{ name: '门店订单', value: 0 }, { name: '个人订单', value: 1 }])
const searchTypeIndex = ref(0)
const updateSearchType = (index: number) => {
	searchTypeIndex.value = index;
	getMescroll().resetUpScroll();
}
const wxPrivacyPopupRef: any = ref(null)
const query = ref<any>(undefined);//查询类型

onLoad((option: any) => {
	console.log(option)
	query.value = 0

	orderState.value = option.status || "";
	orderShowType.value = option.type || "employee";
	if (orderShowType.value == 'employee') {
		create_time.value = getNowMonthDate()
		query.value = undefined

	}
	// getShopOrderStatusFn();
	// #ifdef MP
	nextTick(() => {
		if (wxPrivacyPopupRef.value) wxPrivacyPopupRef.value.proactive();
	})
	// #endif
});

/**
 * 订单查询类型
 */
//日期筛选
const create_time = ref<any>([])
const create_time_str = computed(() => {
	let beginTime = create_time.value[0] ? create_time.value[0].split(' ')[0] : '';
	let endTime = create_time.value[1] ? create_time.value[1].split(' ')[0] : '';
	return beginTime + ' - ' + endTime

})
const timeTypeList = [{
	name: '创建时间',
	status: '0'
}]

const memberDataInfo = ref({

})

import { getUser } from '@/app/api/shopMember';

const getMemberInfo = async () => {
	let userId = ''
	if (uni.getStorageSync('wapShopMember')) {
		userId = uni.getStorageSync('wapShopMember').id;
		const { data: Info } = await getUser(userId)
		memberDataInfo.value = Info

	}
}
//订单筛选
const keyword = ref('')

const selectOrderSearchRef = ref()
const handleSelectOrderSearch = () => {
	selectOrderSearchRef.value.show = true
}
const confirmSearchFn = (data: any) => {
	orderState.value = data.status;
	orderType.value = data.type;
	orderSource.value = data.source;
	keyword.value = data.keyword;
	create_time.value = data.create_time;

	list.value = []
	getMescroll().resetUpScroll();
}
/**
 * 支付弹窗关闭
 */
const payClose = () => {
	nextTick(() => {
		// 评价完成之后，会返回到订单列表，需要请求最新数据
		if (getMescroll()) { getMescroll().resetUpScroll(); }
	})
}
/**
 * 结算
 */

const checkedNum = computed(() => {
	let num = 0
	list.value.forEach((ele: any) => {
		ele.items.forEach((item: any) => {
			item.checked && (num += 1)
		})

	})

	return num
})
const cartCalculateFn = () => {
	total.value.order_money = 0
	let calculateArr: Object = [];
	list.value.forEach((ele: any) => {
		ele.items.forEach((item: any) => {
			if (item.checked) {
				console.log(item.id)
				total.value.order_money += item.leavePrice
				calculateArr.push(item.id);
			}
		})

	})

	if (!calculateArr.length) {
		total.value.order_money = 0

		return false;
	}
}
/**
 * 选择单个商品
 */
const selectOnlyGoods = (data: any = {}) => {
	data.checked = !data.checked
	cartCalculateFn()

}

const settlement = () => {



	if (!checkedNum.value) {
		uni.showToast({ title: '还没有选择订单', icon: 'none' })
		return
	}
	const ids: any = []

	list.value.forEach((ele: any) => {
		ele.items.forEach((item: any) => {
			if (item.checked) {
				console.log(item.id)

				ids.push(item.id);
			}
		})

	})
	console.log(ids)
	uni.setStorage({
		key: 'orderCreateData',
		data: {
			cart_ids: ids,
		},
		success() {
			redirect({ url: '/addon/shop/pages/order/repayment' })
		}
	})
}
onShow(() => {
	const options = uni.getEnterOptionsSync();
	// scene 1038	从另一个小程序返回
	// #ifdef MP
	if (options.scene == 1038) {
		uni.$emit('scene', {
			scene: 1038
		})
		return
	}
	// #endif
	nextTick(() => {
		// 评价完成之后，会返回到订单列表，需要请求最新数据
		if (getMescroll()) { getMescroll().resetUpScroll(); }
	})
})
onMounted(() => {
	console.log('获取会员信息')
	getMemberInfo()
})
onUnload(() => {
	uni.$off('scene')
})

let wap_member_id = uni.getStorageSync('wap_member_id');
let wap_shop_member_id = uni.getStorageSync('wapShopMember').id;

const getShopOrderFn = (mescroll: any) => {
	loading.value = false;
	let api = getShopOrder

	let data: object = {
		pageNo: mescroll.num,
		pageSize: mescroll.size,
		status: orderState.value,
		searchType: 1, // 0 订单列表 1 会员中心
		typeClass: 6, //订单分类 6 欠款订单
		userId: wap_shop_member_id, //用户id
		createTime: create_time.value, //创建时间
		type: orderType.value, //订单类型
		keywords: keyword.value, //关键词
		source: orderSource.value, //订单来源

	};
	api(data).then((res: any) => {
		let newArr = (res.data.list as Array<Object>);
		//设置列表数据
		if (mescroll.num == 1) {
			list.value = []; //如果是第一页需手动制空列表
		}



		list.value = list.value.concat(newArr);

		mescroll.endSuccess(newArr.length);
		cartCalculateFn()
		loading.value = true;
	}).catch(() => {
		loading.value = true;
		mescroll.endErr(); // 请求失败, 结束加载
	})
}





const toLink = (data: any) => {

	redirect({ url: '/addon/shop/pages/shopOrder/detail', param: { order_id: data.id } })


}





</script>
<style>
.order-list .mescroll-body {
	padding-bottom: constant(safe-area-inset-bottom) !important;
	padding-bottom: env(safe-area-inset-bottom) !important;
}

.order-list :deep(.u-count-down__text) {
	font-size: 24rpx !important;
	color: #EF000C !important;
}
</style>
<style lang="scss" scoped>
@import '@/addon/shop/styles/common.scss';

.text-color {
	color: var(--primary-color);
}

.bg-color {
	background-color: var(--primary-color);
}
</style>
